<!DOCTYPE html>
<html lang="zh" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
      xmlns="http://www.w3.org/1999/html">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="content-type" content="text/html;charset=utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <title>WebSocket</title>

  <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<span>org.springframework.security.authentication.UsernamePasswordAuthenticationToken</span></br>
登录账号：<span sec:authentication="name"></span></br>
登录账号：<span sec:authentication="principal.username"></span></br>
principal.enabled：<span sec:authentication="principal.enabled"></span></br>
principal.accountNonLocked：<span sec:authentication="principal.accountNonLocked"></span></br>
凭证：<span sec:authentication="credentials"></span></br>
权限和角色：<span sec:authentication="authorities"></span></br>
<span>org.springframework.security.web.authentication.WebAuthenticationDetails</span></br>
客户端地址：<span sec:authentication="details.remoteAddress"></span></br>
sessionId：<span sec:authentication="details.sessionId"></span></br>

<span>权限控制，按钮是否展示</span></br>
<button sec:authorize="hasAuthority('/insert')">add</button>
<button sec:authorize="hasAuthority('/delete')">del</button>
<button sec:authorize="hasRole('/update')">update</button>
<button sec:authorize="hasRole('/select')">get</button></br>

<input type="text" id="url" value="ws://127.0.0.1:12345/websocket">
<button onclick="openws(url)">open</button>
<br/>

<input type="text" id="message">
<button onclick="send(message)">send</button>
<br/>

<button onclick="closews()">close</button>
<br/>

<a href="/logout">logout</a>
</body>
<script type="text/javascript">
  let ws;

  function openws(url) {
    console.log(url.value);
    if ('WebSocket' in window) {
      ws = new WebSocket(url.value);

      // 接收数据
      ws.onmessage = function (evt) {
        let received_msg = evt.data;
        console.log('接收数据：' + received_msg);
      };

      // 连接建立成功回调
      ws.onopen = function () {
        console.log('[readyState]-' + ws.readyState);
        console.log('Connection established.');
      };
      // 连接失败回调
      ws.onerror = function () {
        console.log('[readyState]-' + ws.readyState);
        console.log('Connection error.');
      };

      // 连接关闭回调
      ws.onclose = function (event) {
        var code = event.code;
        var reason = event.reason;
        var wasClean = event.wasClean;
        console.log('[readyState]-' + ws.readyState);
        console.log('Connection closed.');
        console.log(code, reason, wasClean)
      };
    } else {
      alert('您的浏览器不支持 WebSocket!');
    }
  }

  function send(message) {
    console.log('发送数据：' + message.value);
    ws.send(message);
  }

  function closews() {
    ws.close();
  }
</script>
</html>